package aggregate.aggregator;

import java.util.Date;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import aggregate.aggregator.remote.ContentItem;

public class SAXHandler extends DefaultHandler{

	private int flag1, flag2, flag3, numberUpdates;
	private Vector<ContentItem> updates;
	private String title, body, url, lastNewsTitle;
	
	/****************************************/
	
	public SAXHandler()
	{
		 
		this.updates = new Vector<ContentItem>();
		this.setLastNews("");
	}
	
	/***************************************/
	
	public void setLastNews(String lastNewsTitle)
	{
		this.lastNewsTitle = lastNewsTitle; 
	}
	
	/****************************************/
	
	public void startDocument() throws SAXException
	{
		flag1 = 0;
		flag2 = 0;
		flag3 = 0;
		numberUpdates = 0;
		this.updates.clear();
		this.title = "";
		this.body = "";
		this.url = "";
	}
	
	/*****************************************/
	
	public void startElement(String ns, String local, String name, Attributes atts) throws SAXException
	{
		if(flag3 == 1)
			return; 
		if(name.equals("item"))
			flag1 = 1;
		if(name.equals("title"))
			flag2 = 1;
		if(name.equals("description"))
			flag2 = 2;
		if(name.equals("link"))
			flag2 = 3;
	}
	
	/******************************************/
	
	public void endElement(String ns, String local, String name) throws SAXException
	{
		if(flag3 == 0)
		{
			if(name.equals("item"))
			{
				flag1 = 0;
				if(!this.title.equals(this.lastNewsTitle))
				{
					Date now = new Date();
					ContentItem news = new ContentItem(this.title, this.body, this.url, now.getTime());
					this.updates.add(news);
				}
				this.title = "";
				this.body = "";
				this.url = "";
				
			}
		if(name.equals("title") || name.equals("description") ||name.equals("link"))
			flag2 = 0;
		}
	}
	
	/*******************************************/
	
	public void characters(char[] ch, int start, int length) throws SAXException
	{
		int i;
		
		if((flag1 == 1) && (flag3 == 0))
		{
			if(flag2 == 1)
				{	
					
					for(i=0; i<length; i++)
						this.title += ch[start+i];
					if(this.title.equals(this.lastNewsTitle))
						{
							flag3 = 1;
							return;
						}
				}
			if(flag2 == 2)
				{	
					
				    for(i = 0; i<length; i++)
						this.body += ch[start+i];
					numberUpdates++;
				}
			if(flag2 == 3)
				{
					
					for(i=0; i<length; i++)
						this.url += ch[start+i];
					
				}
			
			
		}
		
	}
	
	/******************************************/
	
	public int numberOfUpdates()
	{
		return this.numberUpdates;
	}
	
	/******************************************/
	
	public Vector<ContentItem> getUpdates()
	{
		return this.updates;
	}
	
	/******************************************/
}
